//根据题目类型激活modal
function activeModal(type,id) {
    $(".answer-block").empty();

    //先显示难度
    $("#general-level").show();

    //根据题目的类型选择给modal添加怎么样的题目
    var parent=$(".answer-block");
    //把input中的id那栏都换成所选题目的id
    $("input[name='questionid']").val(id);

    if(type==1){
        multiple(parent);
        //清空现有选项
        $(".multiple-answers").empty();
        answer=0;
    }else if(type==2){
        tfng(parent);
    }else if(type==3){
        completion(parent);
    }else if(type==4){

    }else if(type==5){
        multiple(parent);
        //清空现有选项
        $(".multiple-answers").empty();
        answer=0;
        //把难度隐藏起来
        $("#general-level").hide();
    }

    getJson(type,id);
}

$.ajaxSetup({
    async : false
});

//绑定章节选择事件
$("#section").change(function () {
    var section=$("#section").val();
    var json={"id":section,"page":1};
    flushTable("http://139.199.200.112/dtpr/index.php?exam-master-questions-examinfo",JSON.stringify(json),"#page","tbody");
});

//给table新增一栏
function addLine(json,url,page,index) {
    console.log(json);
    var tr=$(document.createElement("tr"));
    tr.attr("id",json.questionid);
    //给这一行添加相应的单元格
    tr.append("<td>"+((page-1)*10+index+1)+"</td>");
    tr.append(questionType[json.questiontype-1]);
    tr.append(questionLevel[json.questionlevel-1]);
    tr.append("<td>"+json.question+"</td>");

    //根据题目类型设置modal事件
    tr.append("<td>\n" +
        "    <button class='btn btn-info' onclick='activeModal("+json.questiontype+","+json.questionid+")'>修改</button>\n" +
        "    <button class='btn btn-danger' onclick='removeTopic("+json.questionid+","+json.questiontype+")'>删除</button>\n" +
        "</td>")

    $(".table tbody").append(tr);
}

//触发删除一条题目
function removeTopic(id, type) {
    if(confirm("你确定要删除该题目吗？删除之后不可恢复")){
        $.get("http://139.199.200.112/dtpr/index.php?exam-master-questions-delquestion",{"id":id,"type":type},function (data) {
            var message=JSON.parse(data);
            if(message.code==0){
                if(type==4){
                    var ele=$("#"+id).next();
                    while (ele.next().find("td").get(0).innerHTML=="阅读题内小题"){
                        var next=ele.next();
                        ele.remove();
                        ele=next();
                    }
                }
                $("#"+id).remove();
            }else {
                alert(message.msg);
            }
        })
    }
}

//获取json
function getJson(type,id) {
    $.get("http://139.199.200.112/dtpr/index.php?exam-master-questions-questioncontent",{"id":id,"type":type},function (data) {
        data=JSON.parse(data).data;

        //设置通用属性
        switch (data.questiontype){
            case "1":
            case "2":
            case "3": {
                $("#modal-general").find("input[type='radio'][value='"+data.questionlevel+"']").attr("checked","checked");
                CKEDITOR.instances.generalContainer.setData(data.question);
                CKEDITOR.instances.generalAnswer.setData(data.questiondescribe);
                break;
            }
            case "4": {
                $("#modal-reading").find("input[type='radio'][value='"+data.questionlevel+"']").attr("checked","checked");
                CKEDITOR.instances.container.setData(data.question);
                break;
            }
            case "5": {
                $("#modal-general").find("input[type='radio'][value='"+data.questionlevel+"']").attr("checked","checked");
                CKEDITOR.instances.generalContainer.setData(data.question);
                CKEDITOR.instances.generalAnswer.setData(data.questiondescribe);
                break;
            }
        }

        //设置题目类型
        $("input[name='type']").val(data.questiontype);

        //设置答案
        switch (data.questiontype){
            case "1": initMultiple(data); $("#modal-general").modal(); break;
            case "2": initTfng(data); $("#modal-general").modal(); break;
            case "3": initCompletion(data); $("#modal-general").modal(); break;
            case "4": $("#modal-reading").modal(); break;
            case "5": initMultiple(data); $("#modal-general").modal();  break;
        }
    });
}

//初始化选择题数据
function initMultiple(data) {
    //初始化选项
    for(var i=0;i<data.questionselect.length;i++){
        var input=multipleAdd($(".multiple-answers"));
        input.val(data.questionselect[i]);
    }
    //初始化答案
    for(var i=0;i<data.questionanswer.length;i++){
        var index=JSON.stringify(data.questionanswer[i]).charCodeAt(2)-"A".charCodeAt(0);

        btnSelect($($(".multiple-answers").find(".btn-select").get(index)));
    }
}

//初始化填空题数据
function initCompletion(data) {
    for(var i=0;i<data.questionanswer.length;i++){
        var node;
        //写入第一个选项
        if(i==0){
            node=$(".completion-answer");
        }else {
            node=newCompletion();
        }
        node.find("input[type='text']").val(data.questionanswer[i][0]);
        var addBtn=node.find(".completion-add");
        for(var j=1;j<data.questionanswer[i].length;j++){
            //写入剩下的或选项
            var option=addCompletion(addBtn);
            option.find("input[type='text']").val(data.questionanswer[i][j]);
        }
    }
}

//异步提交题目修改
function submitEdit(type) {
    var formData;
    var parent;
    if(type==1){
        parent=$("#modal-general");
        formData=new FormData($("#modal-general").find(".form-horizontal")[0]);
        formData.append('args[question]',CKEDITOR.instances.generalContainer.getData());
        formData.append('args[questiondescribe]',CKEDITOR.instances.generalAnswer.getData());
    }else {
        parent=$("#modal-reading");
        formData=new FormData($("#modal-reading").find(".form-horizontal")[0]);
        formData.append('args[question]',CKEDITOR.instances.container.getData());
    }

    //表单验证
    if (validationEdit(parent)){
        //表单提交以及回调部分
        $.ajax({
            url:"http://139.199.200.112/dtpr/index.php?exam-master-questions-modifyquestion",
            type:"post",
            processData: false,
            data:formData,
            contentType : false,
            async: false,
            success:function (data) {
                data=JSON.parse(data);
                if(data.code==0){
                    var id=$("input[name='questionid']").val();
                    var tr=$("#"+id);
                    var topic=$(tr.find("td").get(3));
                    //修改表格显示内容
                    if(type==1){
                        $("#modal-general").modal("hide");
                        topic.html(CKEDITOR.instances.generalContainer.document.getBody().getText().substring(0,5));
                    }else {
                        $("#modal-reading").modal("hide");
                        topic.html(CKEDITOR.instances.container.document.getBody().getText().substring(0,5));
                    }

                    topic=$(tr.find("td").get(1));
                    topic.next().remove();
                    topic.after(questionLevel[parent.find("input[name='args[questionlevel]']:checked").val()-1]);
                }else {
                    alert(data.msg);
                }
            },
            error:function () {
                alert("请求发送失败");
            }
        });
    }
}

//初始化判断题数据
function initTfng(data) {
    if(data.questionanswer[0]=='B'){
        $("#tfng-select").find(".btn-default").trigger("click");
    }
}